﻿using System;
using Android.App;
using Android.Graphics;
using Android.Views;
using SkiaSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using TabbedTemplate.Services;
using TabbedTemplate.Views;
using Application = Xamarin.Forms.Application;
using ImageSource = System.IO.MemoryStream;

namespace TabbedTemplate.Droid
{

    public class ImageService : IImageService
    {
        public MainPage MainPage =>
            _mainPage ??= Application.Current.MainPage as MainPage;

        private MainPage _mainPage;

        public static readonly string ImagePath =
            Android.OS.Environment.ExternalStorageDirectory.Path + "/MyFoodDiary";

        public static readonly string SnapPath =
            Android.OS.Environment.ExternalStorageDirectory.Path + "/" + Android.OS.Environment.DirectoryPictures + "/食记";

        private static Activity _currentActivity;

        public void SetActivity(Activity activity) =>
            _currentActivity = activity;

        public async Task Capture()
        {

            var root =
                _currentActivity.Window.DecorView.FindViewById(Android.Resource.Id.Content);
            var viewGroup = (ViewGroup)root;
            var rootView = viewGroup.GetChildAt(1);

            using var OutFileStream =
                new FileStream(ImagePath + "/test11.png", FileMode.Create);


            using (var screenshot = Bitmap.CreateBitmap(rootView.Width,
                rootView.Height, Bitmap.Config.Argb8888))
            {
                var canvas = new Canvas(screenshot);
                rootView.Draw(canvas);


                using (var stream = new MemoryStream())
                {
                    screenshot.Compress(Bitmap.CompressFormat.Png, 90, stream);
                    stream.Position = 0;
                    await stream.CopyToAsync(OutFileStream);
                    //return stream.ToArray();

                }

            }


        }

        public async Task SaveImageAsync(long TimeStamp, byte[] bytes, string fileName)
        {
            if (!Directory.Exists(ImagePath))
            {
                Directory.CreateDirectory(ImagePath);
            }

            var picDirectory = ImagePath + "/" + TimeStamp;
            Directory.CreateDirectory(picDirectory);

            var localPath = picDirectory + "/" + fileName;
            using var OutFileStream =
                new FileStream(localPath, FileMode.Create);
            ImageSource retSource = null;
            if (bytes != null)
            {
                byte[] imageAsBytes = (byte[])bytes;
                retSource = new MemoryStream(imageAsBytes);
            }
            await retSource.CopyToAsync(OutFileStream);

        }

        public void CreateFolder(long TimeStamp)
        {
            if (!Directory.Exists(ImagePath))
            {
                Directory.CreateDirectory(ImagePath);
            }

            var picDirectory = ImagePath + "/" + TimeStamp;
            Directory.CreateDirectory(picDirectory);
        }

        public async Task<IList<byte[]>> ReadImageAsync(long TimeStamp)
        {
            IList<byte[]> streams = new List<byte[]>();
            var targetDirectory = ImagePath + "/" + TimeStamp;
            var res = Directory.GetFiles(targetDirectory);
            for (int i = 0; i < res.Length; i++)
            {
                using (var fileStream = System.IO.File.OpenRead(res[i]))
                using (var memoryStream = new MemoryStream())
                {
                    fileStream.CopyTo(memoryStream);
                    streams.Add(memoryStream.ToArray());
                }
            }
            return streams;
        }

        public void DeleteFolder(long TimeStamp)
        {
            if (Directory.Exists(ImagePath + "/" + TimeStamp))
            {
                var targetDirectory = ImagePath + "/" + TimeStamp;
                var res = Directory.GetFiles(targetDirectory);
                for (int i = 0; i < res.Length; i++)
                {
                    File.Delete(res[i]);
                }

                Directory.Delete(ImagePath + "/" + TimeStamp);
            }
        }


        public async Task SaveSanpImageToAlbumAsync(SKImage skImage)
        {
            if (!Directory.Exists(SnapPath))
            {
                Directory.CreateDirectory(SnapPath);

            }

            var filePath = SnapPath + "/" + DateTime.Now.Ticks + ".png";
            using var OutFileStream =
                new FileStream(filePath, FileMode.Create);

            ImageSource retSource = null;
            var bytes = skImage.Encode(SKEncodedImageFormat.Png, 80).ToArray();

            if (bytes != null)
            {
                byte[] imageAsBytes = (byte[])bytes;
                retSource = new MemoryStream(imageAsBytes);
            }
            await retSource.CopyToAsync(OutFileStream);

        }

    }
}
